package androidx.activity;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayDeque;
import java.util.Iterator;
import o.aa;
import o.kp;
import o.kp.c;
import o.kp.e;
import o.kq;
import o.kv;
import o.z;

public final class OnBackPressedDispatcher {
    final ArrayDeque<z> ˎ;
    @Nullable
    private final Runnable ॱ;

    class LifecycleOnBackPressedCancellable implements kq, aa {
        private final z ˊ;
        private final kp ˋ;
        @Nullable
        private aa ˎ;
        final /* synthetic */ OnBackPressedDispatcher ˏ;

        LifecycleOnBackPressedCancellable(OnBackPressedDispatcher onBackPressedDispatcher, @NonNull kp kpVar, @NonNull z zVar) {
            this.ˏ = onBackPressedDispatcher;
            this.ˋ = kpVar;
            this.ˊ = zVar;
            kpVar.ॱ(this);
        }

        public void ˊ(@NonNull kv kvVar, @NonNull e eVar) {
            if (eVar == e.ON_START) {
                this.ˎ = this.ˏ.ˎ(this.ˊ);
            } else if (eVar == e.ON_STOP) {
                if (this.ˎ != null) {
                    this.ˎ.ˎ();
                }
            } else if (eVar == e.ON_DESTROY) {
                ˎ();
            }
        }

        public void ˎ() {
            this.ˋ.ˋ(this);
            this.ˊ.ˊ(this);
            if (this.ˎ != null) {
                this.ˎ.ˎ();
                this.ˎ = null;
            }
        }
    }

    class a implements aa {
        final /* synthetic */ OnBackPressedDispatcher ˋ;
        private final z ˎ;

        a(OnBackPressedDispatcher onBackPressedDispatcher, z zVar) {
            this.ˋ = onBackPressedDispatcher;
            this.ˎ = zVar;
        }

        public void ˎ() {
            this.ˋ.ˎ.remove(this.ˎ);
            this.ˎ.ˊ(this);
        }
    }

    public OnBackPressedDispatcher() {
        this(null);
    }

    public OnBackPressedDispatcher(@Nullable Runnable runnable) {
        this.ˎ = new ArrayDeque();
        this.ॱ = runnable;
    }

    @MainThread
    @NonNull
    aa ˎ(@NonNull z zVar) {
        this.ˎ.add(zVar);
        aa aVar = new a(this, zVar);
        zVar.ˎ(aVar);
        return aVar;
    }

    @MainThread
    public void ˎ(@NonNull kv kvVar, @NonNull z zVar) {
        kp ac_ = kvVar.ac_();
        if (ac_.ˋ() != c.DESTROYED) {
            zVar.ˎ(new LifecycleOnBackPressedCancellable(this, ac_, zVar));
        }
    }

    @MainThread
    public void ˏ() {
        Iterator descendingIterator = this.ˎ.descendingIterator();
        while (descendingIterator.hasNext()) {
            z zVar = (z) descendingIterator.next();
            if (zVar.ˋ()) {
                zVar.ˏ();
                return;
            }
        }
        if (this.ॱ != null) {
            this.ॱ.run();
        }
    }
}
